package org.demo.redis.controller;

import lombok.extern.slf4j.Slf4j;
import org.demo.datasoureces.entity.UserInfo;
import org.demo.datasoureces.service.UserInfoService;
import org.demo.redis.entity.User;
import org.demo.redis.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/redis")
public class RedisDemoController {

    private static int ExpireTime = 60;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("set")
    @ResponseBody
    public boolean redisset(String key, String value){
        User userEntity =new User();
        Random random = new Random();
        userEntity.setId(userInfoService.queryMaxId()+1L);
        userEntity.setGuid(UUID.randomUUID().toString());
        userEntity.setName("金信"+random.nextInt(1000));
        userEntity.setAge(random.nextInt(100));
        userEntity.setUserDesc("上海疫情管控区");
        userEntity.setCreateTime(new Date());
        log.error("user:"+userEntity);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userEntity,userInfo);
        userInfoService.insertData(userInfo);
//        return  redisUtils.setIfAbsent(key,userEntity);
        return redisUtils.set(key,userEntity);
    }

    @RequestMapping("sethm")
    @ResponseBody
    public boolean redissetHm(String key, Map<String,Object> map){
        if (map.isEmpty()|| map==null){
            map.put("id", new Random().nextInt(1000));
            map.put("guid",UUID.randomUUID().toString());
            map.put("name","新冠");
            map.put("age",3);
            map.put("desc","上海疫情防控");
            map.put("createTime",new Date());
        }
        log.info("map is:"+map);
        return redisUtils.hmset(key,map);
    }

    @RequestMapping("get")
    @ResponseBody
    public Object redisget(String key){
        log.error(key+":"+redisUtils.get(key));
        return redisUtils.get(key);
    }

    @RequestMapping("hget")
    @ResponseBody
    public List<Object> redishget(String id){
        List<String> keys = new ArrayList<>();
        keys.add("userinfo");
        keys.add("user");
        log.error(keys+":"+keys);
        return redisUtils.getDataBatch(keys);
    }

    @RequestMapping("gethm")
    @ResponseBody
    public Map<Object,Object> redisgetHm(String key){
        log.error(key+":"+redisUtils.hmget(key));
        return redisUtils.hmget(key);
    }

    @RequestMapping("expire")
    @ResponseBody
    public boolean expire(String key){
        return redisUtils.expire(key,ExpireTime);
    }
}
